<template>
	<view class="feedback-container">
		<!-- 评论商品 -->
		<view class="sections">
			<image class="goods-img" :src="itemArray[0].orderGoodsList[0].picUrl" mode="aspectFill"
				style="width: 80px; height: 80px; "></image>
			<text>{{itemArray[0].orderGoodsList[0].goodsName}}</text>
		</view>

		<!-- 评论内容输入 -->
		<view class="section">
			评论：
			<textarea v-model="content" placeholder="请详细描述您的问题或建议..." maxlength="500"
				class="feedback-textarea"></textarea>
			<view class="word-count">{{ content.length }}/500</view>
		</view>

		<!-- 图片上传 -->
		<view class="section">
			<view class="section-title">上传图片</view>
			<view class="upload-preview" v-if="picurls && picurls.length > 0">
				<image v-for="(url, index) in picurls" :key="index" :src="url" class="avatar" />
				 <button class="delete-btn" @click="deleteImage(index)">×</button>
			</view>
			<view class="add-more" @tap="chooseImage">
				<text class="el-icon-plus avatar-uploader-icon">+</text>
			</view>
		</view>

		<!-- 评分区域 -->
		<view class="section">
			<view class="section-title">服务评分</view>
			<view class="star-container">
				<view v-for="(item, index) in 5" :key="index" class="star-item" @tap="handleStarClick(index + 1)">
					<!-- 使用 Unicode 星星：★（实心）/ ☆（空心） -->
					<text :class="score >= index + 1 ? 'star-filled' : 'star-empty'">
						{{ score >= index + 1 ? '★' : '☆' }}
					</text>
				</view>
			</view>
			<!-- <view class="section-desc">点击星星选择1-5分</view> -->
		</view>

		<!-- 底部按钮 -->
		<view class="button-group">
			<button class="confirm-btn" @tap="handleSubmit">提交评论</button>
		</view>
	</view>
</template>

<script>
	import {
		getComments
	} from '@/config/api/order.js';
	// import OSS from 'ali-oss';

	export default {
		data() {
			return {
				score: 0,
				showPicker: false, // 控制选择器显示
				content: '', // 评论内容
				picurls: [], // 图片
				itemArray: [],
				ossClient: null // 添加 ossClient
			}
		},
		async onLoad(options) {
			// this.initOSSClient();
			// 1. 解析参数（确保itemArray正确获取）
			try {
				const itemArray = JSON.parse(options.item || '{}');
				if (!itemArray.length) {
					console.error('订单数据为空');
					uni.showToast({
						title: '数据异常，请重试',
						icon: 'none'
					});
					return;
				}
				this.itemArray = itemArray;
				console.log('接收到的数据:', this.itemArray);
				console.log("userid:" + itemArray[0].userId);
			} catch (error) {
				console.error('解析参数失败:', error);
				uni.showToast({
					title: '参数解析失败',
					icon: 'none'
				});
				return;
			}

			// 2. 初始化OSS客户端
		},
		methods: {
			// 新增清除选择方法
			clearSelection() {
				this.selectedType = ''
				this.pickerIndex = 0
			},

			// 选择器变化事件
			pickerChange(e) {
				this.pickerIndex = e.detail.value[0]
			},

			// 确认选择
			confirmSelection() {
				this.selectedType = this.typeOptions[this.pickerIndex]
				this.showPicker = false
			},

			// 取消反馈
			handleCancel() {
				uni.navigateBack()
			},

			// 处理星级点击
			handleStarClick(currentScore) {
				this.score = currentScore; // 设置当前评分
			},

			// 提交评价
			handleSubmit() {
				// 表单验证
				if (!this.content.trim()) {
					uni.showToast({
						title: '请输入评论内容',
						icon: 'none'
					});
					return;
				}
				if (this.score === 0) {
					uni.showToast({
						title: '请选择评分',
						icon: 'none'
					});
					return;
				}

				// 构造请求参数
				const commentData = {
					userId: this.itemArray[0].userId,
					content: this.content,
					star: this.score,
					picUrls: this.picurls.join(','), // 可选参数，后端需允许为空
					valueId: this.itemArray[0].orderGoodsList[0].goodsId,
					productId: this.itemArray[0].orderGoodsList[0].productId,
					orderGoodsId: this.itemArray[0].orderGoodsList[0].id,
					orderId : this.itemArray[0].id,
					type: 3
				};

				// 调用API
				getComments(commentData)
					.then(response => {
						uni.showToast({
							title: '评论成功',
							icon: 'success'
						});
						setTimeout(() => {
							uni.navigateBack();
							// 可选：通知上一页刷新（更精准）
							const pages = getCurrentPages();
							const prevPage = pages[pages.length - 2];
							prevPage.$vm.loadOrders(); // 直接调用上一页方法
						}, 1500);
					})
					.catch(error => {
						console.error('提交失败:', error);
						uni.showToast({
							title: '提交失败，请重试',
							icon: 'none'
						});
					});
			},

			// 初始化OSS客户端
			// initOSSClient() {
			// 	try {
			// 		this.ossClient = new OSS({
			// 			region: 'oss-cn-shenzhen',
			// 			accessKeyId: 'LTAI5tJDNLAHLvTNUxffAYo5',
			// 			accessKeySecret: 'pvXyZSJRoiTEK3HsKms4sk1tzT69Ky',
			// 			bucket: 'jhx-img',
			// 			secure: true,
			// 			// 添加以下配置
			// 			endpoint: 'https://oss-cn-shenzhen.aliyuncs.com',
			// 			cname: false
			// 		});
			// 		console.log('OSS客户端初始化成功');
			// 	} catch (error) {
			// 		console.error('OSS初始化失败:', error);
			// 		uni.showToast({
			// 			title: 'OSS服务初始化失败',
			// 			icon: 'none'
			// 		});
			// 	}
			// },

			// 选择图片
			chooseImage() {
			  const count = 3 - this.picurls.length;
			  if (count <= 0) {
			    uni.showToast({
			      title: `最多上传${3}张图片`,
			      icon: 'none'
			    });
			    return;
			  }
			  uni.chooseImage({
			    count: count,
			    sizeType: ['original', 'compressed'],
			    sourceType: ['album', 'camera'],
			    success: async (res) => {
			      for (let i = 0; i < res.tempFilePaths.length; i++) {
			        const filePath = res.tempFilePaths[i];
			        await this.uploadImage(filePath);
			      }
			    },
			    fail: (err) => {
			      console.error('选择图片失败:', err);
			      uni.showToast({
			        title: '选择图片失败',
			        icon: 'none'
			      });
			    }
			  });
			},
			// 上传图片
			async uploadImage(filePath) {
				try {
					const file = {
						type: await this.getFileType(filePath),
						size: await this.getFileSize(filePath),
						path: filePath
					};
					const isImage = ['image/jpeg', 'image/png', 'image/jpg'].includes(file.type);
					if (!isImage) {
						uni.showToast({
							title: '只能上传JPG/PNG格式的图片!',
							icon: 'none'
						});
						return;
					}

					const isLt3M = file.size / 1024 / 1024 < 3;
					if (!isLt3M) {
						uni.showToast({
							title: '图片大小不能超过3MB!',
							icon: 'none'
						});
						return;
					}

					uni.showLoading({
						title: '上传图片中...'
					});
					const fileName =
						`comment_${Date.now()}_${Math.random().toString(36).substr(2, 9)}.${file.path.split('.').pop()}`;
					const fileData = await this.readFileAsArrayBuffer(file.path);
					console.log(JSON.stringify(file, null, 2));
					const result = await this.ossClient.put(fileName, file);
					this.picurls.push(result.url);
					uni.hideLoading();
				} catch (error) {
					console.error('图片上传失败:', error);
					uni.showToast({
						title: '图片上传失败',
						icon: 'none'
					});
				}
			},

			// 获取文件类型
			getFileType(filePath) {
				return new Promise((resolve, reject) => {
					uni.getFileSystemManager().getFileInfo({
						filePath,
						success: (res) => {
							const ext = filePath.split('.').pop().toLowerCase();
							if (ext === 'jpg' || ext === 'jpeg') {
								resolve('image/jpeg');
							} else if (ext === 'png') {
								resolve('image/png');
							} else {
								reject(new Error('不支持的文件类型'));
							}
						},
						fail: (err) => {
							reject(err);
						}
					});
				});
			},

			// 获取文件大小
			getFileSize(filePath) {
				return new Promise((resolve, reject) => {
					uni.getFileSystemManager().getFileInfo({
						filePath,
						success: (res) => {
							resolve(res.size);
						},
						fail: (err) => {
							reject(err);
						}
					});
				});
			},

			// 读取文件为ArrayBuffer
			async readFileAsArrayBuffer(filePath) {
				return new Promise((resolve, reject) => {
					uni.getFileSystemManager().readFile({
						filePath,
						success: res => {
							resolve(res.data);
						},
						fail: err => {
							reject(err);
						}
					});
				});
			}
		}
	}
</script>

<style>
	/* 手机号输入样式 */
	.phone-input {
		width: 100%;
		height: 48px;
		padding: 0 12px;
		border: 1px solid #eee;
		border-radius: 8px;
		font-size: 15px;
		box-sizing: border-box;
		margin-top: 8px;
	}

	.section-desc {
		font-size: 12px;
		color: #999;
		margin-bottom: 8px;
	}

	/* 图片上传区域 */
	.avatar-uploader {
		width: 100%;
		min-height: 100px;
		border: 1px dashed #ddd;
		border-radius: 8px;
		display: flex;
		justify-content: center;
		align-items: center;
		margin-top: 8px;
	}

	.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 100%;
		height: 100%;
		text-align: center;
	}

	.upload-preview {
		display: flex;
		flex-wrap: wrap;
		padding: 8px;
	}

	.avatar {
		width: 80px;
		height: 80px;
		margin: 4px;
		border-radius: 4px;
	}

	.add-more {
		width: 80px;
		height: 80px;
		border: 1px dashed #ddd;
		border-radius: 4px;
		display: flex;
		justify-content: center;
		align-items: center;
		margin: 4px;
	}

	/* 新增清除按钮样式 */
	.clear-btn {
		width: 24px;
		height: 24px;
		display: flex;
		align-items: center;
		justify-content: center;
		background-color: #f0f0f0;
		border-radius: 50%;
	}

	.feedback-container {
		padding: 20px;
		background-color: #f8f8f8;
		min-height: 100vh;
	}

	.feedback-title {
		font-size: 20px;
		font-weight: bold;
		text-align: center;
		margin-bottom: 20px;
		color: #333;
	}

	.goods-img {
		width: 90px;
		height: 90px;
		border-radius: 12px;
		/* 图片圆角更柔和 */
		box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
		/* 增加图片阴影 */
	}

	.section {
		background-color: #fff;
		border-radius: 12px;
		padding: 16px;
		margin-bottom: 16px;
	}

	.sections {
		background-color: #fff;
		border-radius: 16px;
		/* 容器圆角增大 */
		padding: 20px;
		margin-bottom: 20px;
		display: flex;
		/* 启用弹性布局 */
		align-items: center;
		/* 垂直居中 */
		gap: 16px;
		/* 增大图片文字间距 */
	}

	.sections text {
		font-size: 17px;
		/* 文字增大 */
		color: #2c2c2c;
		/* 深色调文字 */
		line-height: 1.5;
		/* 舒适行高 */
		flex: 1;
		/* 允许文字自动换行 */
		display: -webkit-box;
		-webkit-line-clamp: 2;
		/* 最多显示2行 */
		-webkit-box-orient: vertical;
		overflow: hidden;
		text-overflow: ellipsis;
		/* 超出显示省略号 */
	}

	.section-title {
		font-size: 16px;
		font-weight: bold;
		margin-bottom: 8px;
		color: #333;
	}

	.type-display {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 12px 0;
		color: #666;
	}

	.feedback-textarea {
		width: 100%;
		height: 150px;
		padding: 12px;
		border: 1px solid #eee;
		border-radius: 8px;
		font-size: 14px;
		box-sizing: border-box;
	}

	.word-count {
		text-align: right;
		font-size: 12px;
		color: #999;
		margin-top: 4px;
	}

	/* 选择器样式 */
	.picker-mask {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.5);
		z-index: 999;
		display: flex;
		align-items: flex-end;
	}

	.picker-container {
		width: 100%;
		background-color: #fff;
		border-top-left-radius: 12px;
		border-top-right-radius: 12px;
	}

	.picker-header {
		display: flex;
		justify-content: space-between;
		padding: 12px 20px;
		border-bottom: 1px solid #eee;
	}

	.picker-header text {
		font-size: 16px;
	}

	.picker-header text:last-child {
		color: #07C160;
	}

	.picker-body {
		height: 300px;
	}

	.picker-item {
		line-height: 50px;
		text-align: center;
		font-size: 16px;
	}

	/* 按钮样式 */
	.button-group {
		display: flex;
		justify-content: space-between;
		margin-top: 24px;
	}

	.cancel-btn,
	.confirm-btn {
		width: 48%;
		height: 48px;
		line-height: 48px;
		border-radius: 24px;
		font-size: 16px;
	}

	.cancel-btn {
		background-color: #fff;
		color: #333;
		border: 1px solid #ddd;
	}

	.confirm-btn {
		background-color: #07C160;
		color: #fff;
	}

	.image-container {
		position: relative;
		/* 为按钮提供定位参考 */
	}

	.delete-btn {
		position: absolute;
		top: 4px;
		right: 4px;
		width: 24px;
		/* 按钮宽度 */
		height: 24px;
		/* 按钮高度，与宽度相同实现圆形 */
		display: flex;
		justify-content: center;
		align-items: center;
		background-color: #000;
		/* 黑色背景 */
		color: #fff;
		/* 白色文字 */
		border: none;
		border-radius: 50%;
		/* 圆形 */
		cursor: pointer;
		/* 鼠标悬停变手型 */
		z-index: 1;
		/* 确保按钮在图片上方 */
		font-size: 14px;
		/* 字体大小 */
		padding: 0;
		/* 清除默认内边距 */
	}

	/* 星级评分样式 */
	.star-container {
		display: flex;
		gap: 4px;
		/* 星星间距 */
		margin-top: 8px;
	}

	.star-item text {
		font-size: 40px;
		/* 星星大小 */
		color: #FFD700;
		/* 未选中颜色 */
	}

	.star-filled {
		color: #FFD700;
		/* 选中颜色（金色） */
	}
</style>